/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.resource;

import com.jb.web.context.WebContext;

import java.io.File;
import java.io.FileInputStream;

import java.util.HashMap;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * Responsible for loading resource from a file system. Locale from FacesContext is
 * used to determine the location. It loads from
 * web_top/resources/'session.lang'/resources.properties
 *
 */
public class ResourceManager {
    static private ResourceManager mResourceManager = new ResourceManager();
    private HashMap resources = new HashMap();
    static Log log = LogFactory.getLog(mResourceManager.getClass());

    private ResourceManager() {
    }

    /**
     * Factory Methode for resource manager.
     *
     * @return the singleton resource manager.
     */
    public static ResourceManager getInstance() {
        return mResourceManager;
    }

    /**
     * Gets translated message based on context, and replace tocken with values
     * provided in tockens. Token starts should be in $1, $2 etc.
     *
     * @param ctx
     * @param key
     * @param tokens
     *
     * @return
     */
    public String getMessage(WebContext ctx, String key, String[] tokens) {
        String value = (String) getProperties(ctx).get(key);

        if (value == null) {
            return key;
        }

        for (int i = 0; i < tokens.length; i++) {
            value = value.replaceAll("\\$" + (i + 1), tokens[i]);
        }

        return value;
    }

    /**
     * Returns resources in java.util.Properties. Resources is cached.
     * Timestamps is checked to keep cached updated.
     *
     * @param ctx runtime context.
     * @return list of properties.
     */
    public Properties getProperties(WebContext ctx) {
        String key = makeKey(ctx);
        ResourceManager.ResourceWrapper wrapper = (ResourceWrapper) resources.get(key);
        synchronized (this) {
            if ((wrapper == null) || wrapper.checkDate(ctx)) {
                wrapper = loadResource(ctx);

                if (wrapper != null) {
                    resources.put(key, wrapper);
                }
            }
        }
        return (wrapper != null) ? wrapper.properties : new Properties();
    }

    /**
     * Return resource path used for this application.
     *
     * @return File location of the resource file.
     */
    public static String getResourcePath(WebContext ctx) {
        return ctx.getWebTop() + "/WEB-INF/resources/" + ctx.getSession().getLang();
    }

    private ResourceManager.ResourceWrapper loadResource(WebContext ctx) {
        FileInputStream fis = null;

        try {
            Properties properties = new Properties();
            String resourceLoc = getResourcePath(ctx) + "/resources.properties";
            File file = new File(resourceLoc);
            fis = new FileInputStream(resourceLoc);
            properties.load(fis);

            ResourceManager.ResourceWrapper wrapper = new ResourceManager.ResourceWrapper();
            wrapper.properties = properties;
            wrapper.dateLoaded = file.lastModified();

            return wrapper;
        } catch (Exception e) {
            if(log.isErrorEnabled())
                log.error(this, e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    if(log.isErrorEnabled())
                        log.error(this, e);
                    //
                }
            }
        }
        return null;
    }

    private String makeKey(WebContext ctx) {
        return ctx.getSession().getLang() + ":" + ctx.getWebTop();
    }

    static class ResourceWrapper {
        Properties properties;
        long dateLoaded;
     
        private boolean checkDate(WebContext ctx) {
            try {
                File file = new File(getResourcePath(ctx));
                return file.lastModified() > dateLoaded;
            } catch (Exception e) {
                if(log.isErrorEnabled())
                    log.error(this, e);
            }
            return false;
        }
    }
} //end ResourceManager
